package org.example.back.service.advice;

import org.example.back.entity.user.UserSleep;
import org.example.back.mapper.advice.UserSleepAdviceMapper;
import org.example.back.mapper.user.UserSleepMapper;
import org.example.back.service.healthassistant.HealthAssistantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class UserSleepAdviceService {

    @Autowired
    private UserSleepMapper userSleepMapper;

    @Autowired
    private UserSleepAdviceMapper userSleepAdviceMapper;

    @Autowired
    private HealthAssistantService healthAssistantService;

    public String getDailyAdvice(Integer userId, LocalDate date) {
        String cached = userSleepAdviceMapper.findAdvice(userId, "day", date);
        if (cached != null) return cached;

        UserSleep sleep = userSleepMapper.findUserSleepByDate(userId, date);
        if (sleep == null) {
            return "您昨天没有记录睡眠信息，请保持记录习惯以获得个性化建议。";
        }

        double quality = Double.parseDouble(sleep.getSleepQuality());
        String prompt = String.format(
            "以下是用户 %s 的睡眠数据：入睡时间 %s，起床时间 %s，睡眠评分 %.1f，睡眠感受：%s。睡眠评分满分为五分，请根据此信息提供专业、简明的睡眠建议。",
            date, sleep.getSleepTime(), sleep.getWakeTime(), quality, sleep.getSleepFeeling()
        );

        String advice = healthAssistantService.getAnswerFromLLM(prompt);

        userSleepAdviceMapper.insertAdvice(userId, "day", date, advice);
        return advice;
    }

    public String getWeeklyAdvice(Integer userId) {
        LocalDate startOfWeek = LocalDate.now().minusDays(6);
        String cached = userSleepAdviceMapper.findAdvice(userId, "week", startOfWeek);
        if (cached != null) return cached;

        List<UserSleep> sleepList = userSleepMapper.findUserSleepLastWeek(userId);
        if (sleepList == null || sleepList.isEmpty()) {
            return "过去七天未记录睡眠信息，建议您每天记录，以便获取有效建议。";
        }

        StringBuilder sb = new StringBuilder("以下是用户过去七天的睡眠记录：\n");
        for (UserSleep sleep : sleepList) {
            double quality = Double.parseDouble(sleep.getSleepQuality());
            sb.append(String.format("%s：入睡 %s，起床 %s，评分 %.1f，感受：%s\n",
                    sleep.getSleepDate(), sleep.getSleepTime(), sleep.getWakeTime(),
                    quality, sleep.getSleepFeeling()));
        }
        sb.append("睡眠平均评分满分为五分，请基于以上数据，为用户提供一份本周睡眠建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());

        userSleepAdviceMapper.insertAdvice(userId, "week", startOfWeek, advice);
        return advice;
    }

    public String getMonthlyAdvice(Integer userId) {
        LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1);
        String cached = userSleepAdviceMapper.findAdvice(userId, "month", startOfMonth);
        if (cached != null) return cached;

        List<Map<String, Object>> weekData = userSleepMapper.findUserSleepByWeekInMonth(userId);
        if (weekData == null || weekData.isEmpty()) {
            return "最近一个月没有睡眠数据，无法提供建议。请持续记录睡眠情况。";
        }

        StringBuilder sb = new StringBuilder("以下是用户过去一个月按周统计的睡眠信息：\n");
        for (Map<String, Object> week : weekData) {
            sb.append(String.format("周 %s：共记录 %s 天，平均睡眠时长 %s 小时，平均评分 %s\n",
                    week.get("week_range"), week.get("sleep_days"),
                    week.get("total_sleep_hours"), week.get("avg_sleep_quality_score")));
        }
        sb.append("睡眠平均评分满分为五分，请基于以上统计信息，为用户提供月度睡眠建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());

        userSleepAdviceMapper.insertAdvice(userId, "month", startOfMonth, advice);
        return advice;
    }

    // 每天凌晨调用，删除所有“日”建议缓存
    public void cleanDailyAdviceCache() {
        userSleepAdviceMapper.deleteAdviceByType("day");
    }

    // 睡眠数据更新时调用，删除所有“周”和“月”建议缓存
    public void cleanWeekAndMonthAdviceCache(Integer userId) {
        userSleepAdviceMapper.deleteAdviceByUserAndType(userId,"day");
        userSleepAdviceMapper.deleteAdviceByUserAndType(userId,"week");
        userSleepAdviceMapper.deleteAdviceByUserAndType(userId,"month");
    }
}
